package com.huge.rpc;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * 表示服务
 * @author jihu
 * @date 2020/10/5
 */
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ServiceDescriptor {
    private String clazz;
    private String method;
    private String returnType;
    private String[] parameterTypes;

    public static ServiceDescriptor from(Class clazz, Method method){
        Class<?>[] parameterClasses = method.getParameterTypes();
        String[] parameterTypes = new String[parameterClasses.length];
        for (int i = 0; i < parameterClasses.length; i++) {
            parameterTypes[i] = parameterClasses[i].getName();
        }
        ServiceDescriptor serviceDescriptor =
                    ServiceDescriptor.builder()
                                     .clazz(clazz.getName())
                                     .method(method.getName())
                                     .returnType(method.getReturnType().getName())
                                     .parameterTypes(parameterTypes)
                                     .build();
        return serviceDescriptor;
    }

    @Override
    public int hashCode() {
        return toString().hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if(this == obj) return true;
        if(obj == null || getClass() != obj.getClass()) return false;

        ServiceDescriptor that = (ServiceDescriptor) obj;
        return this.toString().equals(that.toString());
    }

    @Override
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        return buffer.append("clazz=")
                     .append(clazz)
                     .append("method=")
                     .append(method)
                     .append("returnType=")
                     .append(returnType)
                     .append("parameterTypes=")
                     .append(Arrays.toString(parameterTypes))
                     .toString();
    }
}
